package org.example.easybuy.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.jcraft.jsch.SftpException;
import com.mysql.cj.util.StringUtils;
import org.example.easybuy.annotation.PermissionCheck;
import org.example.easybuy.entity.Product;
import org.example.easybuy.service.ProductService;
import org.example.easybuy.util.CustomResult;
import org.example.easybuy.util.SftpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/admin")
public class ProductController {

    @Autowired
    private ProductService productService;

    ObjectMapper objectMapper=new ObjectMapper();
    @PermissionCheck("1")
    @GetMapping("/getProductPage")
    public CustomResult getProductPageInfo(@RequestParam Map<String,Object> params)
    {
        if(!StringUtils.isNullOrEmpty((String)params.get("name")))
        {
            params.put("name","%"+params.get("name")+"%");
        }
        if(!StringUtils.isNullOrEmpty((String)params.get("creationDate")))
        {
            params.put("creationDate","%"+params.get("creationDate")+"%");
        }
        PageInfo<Product> pageInfo=productService.getProductPageInfo(params);

        return CustomResult.successResult().addResult("pageInfo",pageInfo);
    }
    @PermissionCheck("1")
    @GetMapping("/deleteProduct")
    public CustomResult deleteProduct(String id)
    {
        try {
            if(productService.deleteProduct(id)) {
                return CustomResult.successResult().addResult("isDelete", "yes");
            }
        } catch (Exception e) {
            return CustomResult.errorResult(500,"删除出错了").addResult("isDelete","no");
        }
        return CustomResult.errorResult(500,"删除出错了").addResult("isDelete","no");
    }

    @PermissionCheck({"1","0"})
    @GetMapping("/getProductById")
    public CustomResult getProductById(String id)
    {
        return CustomResult.successResult().addResult("product",productService.selectById(id));
    }
    @PermissionCheck("1")
    @GetMapping("/getUpdateLevel")
    public CustomResult getUpdateLevel(int type,int id)
    {
        return CustomResult.successResult().addResult("list",productService.getUpdateLevel(type,id));
    }
    @PermissionCheck("1")
    @PostMapping("/updateProduct")
    public CustomResult updateProduct(@RequestParam("fileImg") MultipartFile file,@RequestParam("product") String productStr) throws IOException, SftpException {
        Product product=objectMapper.readValue(productStr,Product.class);
        if(!file.isEmpty())
        {
            String fileName=file.getOriginalFilename();
            String fileExtend=fileName.substring(fileName.lastIndexOf("."));
            if(fileExtend.equals(".jpg")||fileExtend.equals(".png")||fileExtend.equals(".jpeg"))
            {
                if(file.getSize()>5*1024*1024)
                {
                    return CustomResult.successResult().addResult("info","outSize");
                }
                String newFileName= UUID.randomUUID().toString()+fileExtend;
                InputStream is=file.getInputStream();

                SftpUtil sftp = new SftpUtil("lxt", "200323", "192.168.2.106", 22);
                //登录
                sftp.login();
                //输出到服务器特定目录
                sftp.upload("/home/lxt/my-file/images", newFileName, is);

                //退出
                sftp.logout();
                product.setFileName(newFileName);
            }
            else{
                return CustomResult.successResult().addResult("info","noImg");
            }
        }
        try {
            productService.updateProduct(product);
        } catch (Exception e) {
            return CustomResult.successResult().addResult("isUpdate","fail");
        }
        return CustomResult.successResult().addResult("isUpdate","success");
    }
    @PermissionCheck("1")
    @PostMapping("/addProduct")
    public CustomResult addProduct(@RequestParam("fileImg") MultipartFile file,@RequestParam("product") String productStr) throws IOException, SftpException {
        Product product=objectMapper.readValue(productStr,Product.class);
        if(!file.isEmpty())
        {
            String fileName=file.getOriginalFilename();
            String fileExtend=fileName.substring(fileName.lastIndexOf("."));
            if(fileExtend.equals(".jpg")||fileExtend.equals(".png")||fileExtend.equals(".jpeg"))
            {
                if(file.getSize()>5*1024*1024)
                {
                    return CustomResult.successResult().addResult("info","outSize");
                }
                String newFileName= UUID.randomUUID().toString()+fileExtend;
                InputStream is=file.getInputStream();

                SftpUtil sftp = new SftpUtil("lxt", "200323", "192.168.2.106", 22);
                //登录
                sftp.login();
                //输出到服务器特定目录
                sftp.upload("/home/lxt/my-file/images", newFileName, is);

                //退出
                sftp.logout();
                product.setFileName(newFileName);
            }
            else{
                return CustomResult.successResult().addResult("info","noImg");
            }
        }
        product.setIsDelete(0);
        product.setCreationDate(new Date());
        try {
            productService.addProduct(product);
        } catch (Exception e) {
            return CustomResult.successResult().addResult("isAdd","fail");
        }
        return CustomResult.successResult().addResult("isAdd","success");
    }
    @PermissionCheck("1")
    @GetMapping("/checkProductName")
    public CustomResult checkProductName(@RequestParam Map<String,Object> params)
    {
        Product product=productService.checkProductName(params);
        if(product==null)
        {
            return CustomResult.successResult().addResult("isExist","no");
        }
        return CustomResult.successResult().addResult("isExist","yes").addResult("product",product);
    }

}
